package com.mh.mh.netty.protocal.endecoder;

import com.mh.mh.netty.protocal.MyLsProtocol;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 客户端Handler
 * @author
 */
public class FixedLengthClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 客户端一旦与服务端建立好连接，就会触发该方法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        // 发送消息
//        String data = "I am client ...";
//        JSONObject json = new JSONObject();
//        json.put("tip",data);
//
//        // 获取要发送信息的字节数组
//        byte[] content = json.toString().getBytes();
//        // 要发送信息的长度
//        int contentLength = content.length;
//        MyLsProtocolMine protocol = new MyLsProtocolMine(contentLength, content);
//        ctx.writeAndFlush(protocol);

        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss SSS");// 设置日期格式
        String strDate = df.format(new Date());
        String strMsg = "你好，服务器"+strDate;

        strMsg = CommonTools.formatString(strMsg, CommonTools.FIXEDLENGTHFRAME_LENGTH);
        ctx.writeAndFlush(Unpooled.copiedBuffer(strMsg, CharsetUtil.UTF_8));


    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // 用于获取客户端发来的数据信息
            MyLsProtocol body = (MyLsProtocol) msg;
            System.out.println("Client接收的服务端的信息：" + body.toString());
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
